<?php

class Rating_m extends CI_Model {

	function get_rating($id, $type = 'CN'){
		$this->db->where('id', $id);
		$this->db->where('type', $type);
		return 
		$this->db->get('ratings')->row();
		echo $this->db->last_query();die;
	}

	function save($data){
		$this->db->select('*');
		$this->db->where('id', $data['id']);
		$this->db->where('type', $data['type']);
		$result	= $this->db->get('ratings')->result();
		// echo $this->db->last_query();die;
		if($result){
			$sql	=	"UPDATE ratings SET total_votes = total_votes + 1, total_value = total_value + {$data['value']} WHERE id={$data['id']} AND type = '{$data['type']}'";
			$this->db->query($sql);
		}else{
			$this->db->insert('ratings', array(
				'id'				=>	$data['id'],
				'type'			=>	$data['type'],
				'total_votes'	=>	1,
				'total_value'	=>	$data['value'],
			));
		}
		$this->db->select('*');
		$this->db->where('id', $data['id']);
		$this->db->where('type', $data['type']);
		return 
		$this->db->get('ratings')->row();
		echo $this->db->last_query();die;
	}
}
